<?php

namespace App\Http\Controllers;

use App\Models\Task;
use App\Models\TaskApplication;
use App\Models\Settlement;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class AutoSettlementController extends Controller
{
    /**
     * 自动创建任务完成结算
     */
    public function createTaskCompletionSettlement(Request $request)
    {
        $request->validate([
            'task_id' => 'required|exists:tasks,id',
            'task_application_id' => 'required|exists:task_applications,id',
        ]);

        $task = Task::findOrFail($request->task_id);
        $taskApplication = TaskApplication::findOrFail($request->task_application_id);

        // 验证任务状态
        if ($task->status !== 'completed') {
            return response()->json([
                'success' => false,
                'message' => '任务尚未完成，无法创建结算'
            ], 400);
        }

        // 验证申请状态
        if ($taskApplication->status !== 'approved') {
            return response()->json([
                'success' => false,
                'message' => '申请未通过，无法创建结算'
            ], 400);
        }

        // 检查是否已存在结算记录
        $existingSettlement = Settlement::where('task_id', $task->id)
                                       ->where('task_application_id', $taskApplication->id)
                                       ->where('type', 'task_completion')
                                       ->first();

        if ($existingSettlement) {
            return response()->json([
                'success' => false,
                'message' => '该任务已存在结算记录'
            ], 400);
        }

        DB::beginTransaction();
        try {
            // 计算结算金额
            $amount = $this->calculateSettlementAmount($task, $taskApplication);

            $settlement = Settlement::create([
                'tenant_id' => $task->tenant_id,
                'task_id' => $task->id,
                'task_application_id' => $taskApplication->id,
                'type' => 'task_completion',
                'amount' => $amount,
                'description' => "任务完成结算 - {$task->title}",
                'status' => 'pending',
                'created_by' => null, // 系统自动创建
            ]);

            DB::commit();

            Log::info('自动创建任务完成结算', [
                'settlement_id' => $settlement->id,
                'task_id' => $task->id,
                'amount' => $amount
            ]);

            return response()->json([
                'success' => true,
                'message' => '结算记录创建成功',
                'data' => $settlement->load(['task', 'taskApplication'])
            ], 201);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('自动创建结算失败', [
                'task_id' => $task->id,
                'error' => $e->getMessage()
            ]);

            return response()->json([
                'success' => false,
                'message' => '创建结算失败：' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * 批量处理完成任务的结算
     */
    public function batchCreateSettlements()
    {
        // 查找已完成但未创建结算的任务
        $completedTasks = Task::where('status', 'completed')
                             ->whereDoesntHave('settlements', function ($query) {
                                 $query->where('type', 'task_completion');
                             })
                             ->with(['approvedApplications'])
                             ->get();

        $createdCount = 0;
        $errors = [];

        foreach ($completedTasks as $task) {
            foreach ($task->approvedApplications as $application) {
                try {
                    DB::beginTransaction();

                    $amount = $this->calculateSettlementAmount($task, $application);

                    Settlement::create([
                        'tenant_id' => $task->tenant_id,
                        'task_id' => $task->id,
                        'task_application_id' => $application->id,
                        'type' => 'task_completion',
                        'amount' => $amount,
                        'description' => "任务完成结算 - {$task->title}",
                        'status' => 'pending',
                        'created_by' => null,
                    ]);

                    DB::commit();
                    $createdCount++;
                } catch (\Exception $e) {
                    DB::rollBack();
                    $errors[] = "任务 {$task->id} 申请 {$application->id}: {$e->getMessage()}";
                }
            }
        }

        Log::info('批量创建结算完成', [
            'created_count' => $createdCount,
            'error_count' => count($errors)
        ]);

        return response()->json([
            'success' => true,
            'message' => "批量创建完成，成功创建 {$createdCount} 条结算记录",
            'data' => [
                'created_count' => $createdCount,
                'errors' => $errors
            ]
        ]);
    }

    /**
     * 计算结算金额
     */
    private function calculateSettlementAmount(Task $task, TaskApplication $application)
    {
        // 基础金额
        $baseAmount = $task->budget;

        // 根据任务类型和结算周期计算
        switch ($task->settlement_cycle) {
            case 'daily':
                // 按日结算
                $amount = $baseAmount;
                break;
            case 'weekly':
                // 按周结算
                $amount = $baseAmount;
                break;
            case 'monthly':
                // 按月结算
                $amount = $baseAmount;
                break;
            case 'project':
                // 按项目结算
                $amount = $baseAmount;
                break;
            default:
                $amount = $baseAmount;
        }

        // 可以根据业务需求添加其他计算逻辑
        // 例如：绩效奖金、扣款等

        return $amount;
    }
}